package com.canbot.u05.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.BuildConfig;
import com.canbot.u05.R;
import com.canbot.u05.activity.admin.TokenProccessor;
import com.canbot.u05.activity.firstguide.PasswordSetActivity;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.ChestSocketManager;
import com.canbot.u05.socket.HeadSocketManager;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.CrashHandler;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.SPUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.utils.WifiUtils;
import com.canbot.u05.utils.XunFeiYuYingUtils;
import com.canbot.u05.versionupdate.VersionCheckMgr;
import com.canbot.u05.view.CenterCommonHintDialog;
import com.canbot.u05.view.CenterDialog2;
import com.canbot.u05.view.CenterErrorDialog;

import java.util.HashMap;

/**
 * 主页
 * 管理员权限验证流程：
 *
 *  三方联网成功 ↓
 *
 *     查询管理员信息 ↓
 *
 *        （1）已经设置过管理员--->验证token ↓
 *
 *                              服务器没有保存对应token ---> 进入密码验证界面 ↓
 *                                                        验证成功 --->返回主页--->保存token--->结束
 *                                                        验证失败 --->返回主页--->断开三方联网
 *
 *                              服务器保存有token ↓
 *                                              token有效 --->验证成功--->更新token有效期--->结束
 *
 *                                              token过期 ↓
 *                                                      进入密码验证界面 ↓
 *                                                                  验证成功 --->返回主页--->更新token--->结束
 *                                                                  验证失败 --->返回主页--->断开三方联网
 *                                              服务器异常 ↓
 *                                                      进入密码验证界面 ↓
 *                                                                   验证成功 --->返回主页--->更新token--->结束
 *                                                                   验证失败 --->返回主页--->断开三方联网
 *
 *       （2）没有设置管理员 --->进入首次引导界面 ↓
 *                                           设置管理员密码--->选择场景应用 ↓
 *                                                                 上传管理员密码
 *                                                                 上传场景应用信息
 *                                                                 上传token信息
 *
 *       （3）服务器异常 ---> 连续3次服务器异常断开连接--->结束
 *
 */

public class MyRobotActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = "MyRobotActivity";
		
        private static final int CONNECTING = 0;

        private CenterDialog2 centerDialog;

        private CenterDialog2 mSuccessDialog;

        private CenterDialog2 mConnectingDialog;

        private CenterCommonHintDialog mConfirmConnectionDialog;

        private boolean isFirst = false;

        private CenterErrorDialog mFailureDialog;

        private Button btDisconnect;

        private Button btConn;

        private static final int CONNECTION_TIME = 60 * 1000;

        private  boolean disconnectNetSuccess = false;
		
        private  long disconnectTime;

        private static final int REQUEST_CODE = 101;

        private static final int PERMISSION_REQUEST_CODE = 102;

        private Dialog loadingDialog;
		
        private ToastTools toastTools;

        private  boolean isVerifying;
		
		  private  boolean isConnect = false;

        private  String   headMac = "";
		
        private CenterCommonHintDialog verifyFaildeDialog;
		

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_my_robot);
                toastTools = ToastTools.newInstance(this);
                findViewById(R.id.icon_control).setOnClickListener(this);
                findViewById(R.id.icon_editor).setOnClickListener(this);
                btDisconnect = (Button) findViewById(R.id.btn_disconnect_net);
                btConn = (Button) findViewById(R.id.btn_conn_net);
                TextView textName = (TextView) findViewById(R.id.text_name);
                final String nameHolder = getResources().getString(R.string.my_uu_name);
                final String name = String.format(nameHolder, Config.ROBOT_NAME);
                textName.setText(name);
                XunFeiYuYingUtils.getInstance().init(getApplicationContext());
				connectRobot();
        }
		
		     private void connectRobot(){
				 disconnectNetSuccess = false;
				 mConnectingDialog = new CenterDialog2(this, CONNECTING);
                 mConnectingDialog.show();
                 setDialogWindowAttr(mConnectingDialog, this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
              
			  final String currentSSID = getCurrentSSID();
                if (WifiUtils.isU05Wifi(currentSSID)) {
                        //显示的是设置机器人，说明目前还没有三方组网.
                       
						
						final HashMap<String, Object> hasMap = new HashMap<>(1);
                hasMap.put("type", "0");
                OkHttpUtils.upLoadFile(IpMsgConst.HTTP_URL_CHEST + "connectPad", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                isConnect = true;
								   final JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class) ;

								   headMac=jsonResponse.getResult().toString()  ;
								      Log.e(TAG," jsonResponse.result:" +  jsonResponse.getResult().toString());
								  

							 HeadSocketManager.getInstance().init(MyRobotActivity.this, new Runnable() {
                                                        @Override
                                                        public void run() {
                                                        }
                                                });

                                                ChestSocketManager.getInstance().init(MyRobotActivity.this, new Runnable() {
                                                        @Override
                                                        public void run() {                                                                
                                                        }
                                                });
							
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                mConnectingDialog.dismiss();
                                                btDisconnect.setVisibility(View.VISIBLE);
                                                btConn.setVisibility(View.GONE);
												toastTools.showText("连接成功");
                                                verifyAdmin();

                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                isConnect = false;
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                mConnectingDialog.dismiss();
                                                btDisconnect.setVisibility(View.GONE);
                                                btConn.setVisibility(View.VISIBLE);
                                                isConnect = false;
                                              toastTools.showText("连接失败，请重试");
                                        }
                                });
                        }
                });
                }
                else {
                       toastTools.showText(getString(R.string.not_connected_chest_hotspot));
                }
        }
		
		
		        @Override
        protected void onResume() {
                super.onResume();
//                Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
                switchConnBtn();
                this.isVerifying = false ;
        }

        private int verifyCount = 0;
        /**
         * 检测管理员权限
         */
        private void verifyAdmin() {
                if (isVerifying){
                        Log.e(TAG,"isVerifying");
                        return;
                }

                isVerifying = true;
                verifyCount++;
                if (verifyCount > 3){   //获取管理员信息失败次数超过3次，断开网络连接
                    toastTools.showText("获取管理员数据失败");
                    cancelDialog();
                    verifyFailedHandler();
                    return;
                }

                Log.e(TAG,"verifyAdmin");

                final HashMap<String,String> params = new HashMap<>();
                params.put("adminType","queryAdmin");
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", params, new OkHttpUtils.OkHttpCallBack() {
                    @Override
                    public void onSuccess(final String result) {
                        Log.e(TAG,"result:" + result);
                            final JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class);
                            if (jsonResponse.getRc() == -1){ //未设置管理员信息，进入首次引导界面
                                    Log.e(TAG,"未设置管理员信息，进入首次引导界面");
                                    verifyCount = 0;
                                    runOnUiThread(() -> {
                                            startActivity(MyRobotActivity.this, PasswordSetActivity.class);
                                            cancelDialog();
                                    });


                            }else if (jsonResponse.getRc() == 0){ //已设置管理员,查询token
                                    Log.e(TAG,"已设置管理员,token查询");
                                    verifyCount = 0;
                                    verifyToken();
                            }
                    }

                    @Override
                    public void onFailure() {
                        Log.e(TAG,"Admin onFailure:获取管理员数据失败");
                        isVerifying = false;
                        handler.postDelayed(() -> verifyAdmin(),500);

                    }
                });
        }
		
		     private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
					
			 }}  ;

        private void verifyFailedHandler() {
                isVerifying = false;
                verifyCount = 0;
                verifyFaildeDialog = new CenterCommonHintDialog(this,9);
                verifyFaildeDialog.setCancelable(false);
                verifyFaildeDialog.setCanceledOnTouchOutside(false);
                verifyFaildeDialog.show();
                verifyFaildeDialog.setListner(id -> {
                     switch (id)  {
                             case R.id.dialog_verify_failed_reconnect:
                                  
                                     verifyFaildeDialog.dismiss();
                                     connectRobot();
                                     break;
                             case R.id.dialog_verify_failed_disconnect:
                                     verifyFaildeDialog.dismiss();
                                     disconnectNet();
                                     break;
                             default:
                                     break;


                     }
                });
        }

        /**
         * 检测token有效性
         */
        private void verifyToken() {
                final String token = getToken();

                final HashMap<String,String> params = new HashMap<>();
                params.put("adminType","tokenAlive");
                params.put("tokenAlive",token);

                Log.e(TAG,"token:" + token);

                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", params, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(final String result) {
                                final JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class);
                                if (jsonResponse.getRc() == -1){//token无效,跳转密码验证界面
                                        Log.e(TAG,"token无效");
                                        runOnUiThread(() -> {
                                                final Intent intent = new Intent(MyRobotActivity.this,PassWordActivity.class);
                                                startActivityForResult(intent,REQUEST_CODE);
                                                cancelDialog();
                                        });

                                }else if (jsonResponse.getRc() == 0){ //token在有效期,验证成功,重新保存token有效时间,验证结束
                                        Log.e(TAG,"token有效");
                                        toastTools.showText("验证成功");
                                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_CONN_SUCCESS, "conn success");
                                        addToken();
                                        runOnUiThread(() -> cancelDialog());
                                        isVerifying = false;

                                }
                        }

                        @Override
                        public void onFailure() {//查询token失败（通过验证密码登录）
                                Log.e(TAG,"token onFailure");
                                runOnUiThread(() -> {
                                        final Intent intent = new Intent(MyRobotActivity.this,PassWordActivity.class);
                                        startActivityForResult(intent,REQUEST_CODE);
                                        cancelDialog();
                                });
                        }
                });
        }

        /**
         * 获取token
         * @return
         */
        private String getToken() {
                String token = SPUtils.getString(this, "token", "");
                if (TextUtils.isEmpty(token)){
                        Log.e(TAG,"token is empty");
                        token = TokenProccessor.getInstance().makeToken();
                }
                return token;
        }


        //设置对话框显示
        public static void setDialogWindowAttr(final Dialog dlg, final Context ctx, final int width, final int height) {
                final Window window = dlg.getWindow();
                final WindowManager.LayoutParams params = window.getAttributes();
                params.gravity = Gravity.CENTER;
                params.width = width;//宽高可设置具体大小
                params.height = height;
                dlg.getWindow().setAttributes(params);
        }

        @Override
        public void onClick(View view) {
                if (!isConnect){
                        ToastTools.newInstance(this).showText("请先连接机器人");
                        return;
                }

                switch (view.getId()) {
                        case R.id.icon_control:
                                startActivity(this, EditorActivity.class);
                                break;
                        case R.id.icon_editor:
                                startActivity(this, ControlCenterActivity.class);
                                break;
                        default:
                                break;
                }

        }

        public void disconnectNet(View view) {
            disconnectNet();
        }

        /**
         * 断开网络，同时给胸口和头部发送消息
         * 断开机器人button
         *
         */
        private void disconnectNet() {
                if (!WifiUtils.isU05Wifi(getCurrentSSID())) {
                        ToastTools.newInstance(this).showText(getString(R.string.not_connected_chest_hotspot));
                        return ;
                }

                handler.removeCallbacksAndMessages(null);
//                setDialogWindowAttr(centerDialog, this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
                disconnectTime = System.currentTimeMillis();
				
				 final HashMap<String, Object> hasMap = new HashMap<>(1);
                hasMap.put("type", "1");
                OkHttpUtils.upLoadFile(IpMsgConst.HTTP_URL_CHEST + "connectPad", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                isConnect = false;
							
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                btDisconnect.setVisibility(View.GONE);
                                                btConn.setVisibility(View.VISIBLE);
												 toastTools.showText("断开成功");
                                                HeadSocketManager.getInstance().destroy();
                                                ChestSocketManager.getInstance().destroy();
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
							  runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                toastTools.showText("断开失败，请重试");
                                        }
                                });
                        }
                });
				
				
				
        }

        /**
         * 三方组网
         * 连接机器人button
         *
         */
        public void connNet(View view) {
                connectRobot();
        }

   

        private Dialog mUpdateDialog;

        /**
         * 版本更新检测
         */
        private void checkNewVersion() {
            String padMac = CrashHandler.getLocalMacAddressFromIp(this);
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(MyRobotActivity.this)) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, PERMISSION_REQUEST_CODE);
                } else {
                    VersionCheckMgr.INSTANCE.checkNewVersion(this, BuildConfig.BRNACH_NAME, BuildConfig.VERSION_CODE, padMac, headMac, false);
                }
            }
        }

      

        @Override
        protected void onPause() {
                super.onPause();
                disconnectNetSuccess = false;
                if (mUpdateDialog != null && mUpdateDialog.isShowing()) {
                        mUpdateDialog.dismiss();
                }
        }

        private void switchConnBtn() {
                        btDisconnect.setVisibility(View.VISIBLE);
                        btConn.setVisibility(View.GONE);
        }

        /**
         * 密码验证界面返回结果
         */
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                Log.e(TAG,"onActivityResult  "+requestCode+"  "+resultCode);

                if (requestCode == REQUEST_CODE){
                        if (resultCode == Activity.RESULT_OK){  //密码验证通过，管理员验证完成，更新token保存时间
                                isVerifying = false;
                                addToken();
                                MsgSendUtils.sendStringMsg(MsgType.SEND_CONN_SUCCESS, "conn success");

                        }else{//管理员认证失败，断开三方联网
                                disconnectNet();
                        }
                } else if (requestCode == PERMISSION_REQUEST_CODE) {
                        if (Build.VERSION.SDK_INT >= 23) {
                                if (!Settings.canDrawOverlays(this)) {
                                        // SYSTEM_ALERT_WINDOW permission not granted...
                                        Toast.makeText(MyRobotActivity.this, "permission not granted", Toast.LENGTH_SHORT);
                                } else {

                                }
                        }
                }
        }

        /**
         * 添加/更新token（登录成功后，重新保存token（有效期为7天））
         */
        private void addToken() {
                final String token = getToken();
                final HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("adminType","addToken");
                hasMap.put("addToken",token);

                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "admin", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(final String result) {
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                if (strMsgBean.getRc() == 0){
                                        Log.e(TAG,"token数据保存成功");
                                        SPUtils.saveString(MyRobotActivity.this,"token", token); //token保存本地
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        checkNewVersion();
                                                }
                                        });
                                }else{
                                        Log.e(TAG,"token数据保存失败!");
                                }
                        }
                        @Override
                        public void onFailure() {
                                Log.e(TAG,"token数据保存失败,服务器异常!");
                        }
                });
        }

        /**
         * 取消加载的Dialog
         */
        private void cancelDialog() {
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.cancel();
            }
        }

        @Override
        public void onBackPressed() {
        }
		
		        /**
         * 跳转到其他activity
         */
        protected void startActivity(Context context, Class<?> cls) {
                final Intent intent = new Intent(context, cls);
                startActivity(intent);
        }
		
		     private String getCurrentSSID() {
                //获取当前连接的wifi信息
                final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
                final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo != null) {
                        return wifiInfo.getSSID();
                }
                return null;
        }

		
}
